﻿using HZY.Framework.DependencyInjection;
using Mapster;
using NewLife;
using YR.Framework.Core;
using YR.Framework.Freesql;

namespace SingleWpfProject
{
    public class ProjectAppService : CURDAppService<ProjectAddDto, ProjectDeleteDto, ProjectUpdateDto, ProjectPageQueryDto, PageResult<ProjectPageQueryResultDto>, ProjectEntity, long>, IScopedSelfDependency
    {
        public ProjectAppService() : base(Consts.DbKey)
        {
        }

        /// <summary>
        /// 新增项目
        /// </summary>
        /// <param name="add"></param>
        /// <returns></returns>
        public override async Task<BaseResult> AddAsync(ProjectAddDto add)
        {
            //TODO 业务校验及操作
            ProjectEntity entity = add.Adapt<ProjectEntity>();

            var affRows = await InsertAsync(entity);
            return new BaseResult().Success($"影响行数:{affRows}");
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="delete"></param>
        /// <returns></returns>
        public override async Task<BaseResult> DeleteAsync(ProjectDeleteDto delete)
        {
            await DeleteByConditionAsync(p => p.Id == delete.Id);

            return new BaseResult().Success("删除项目成功");
        }

        /// <summary>
        /// 查询项目
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public override async Task<PageResult<ProjectPageQueryResultDto>> QueryDataAsync(ProjectPageQueryDto query)
        {
            //TOOD: 支持分页查询案例
            //TODO: 支持精确、模糊查询案例

            PageResult<ProjectPageQueryResultDto> result = new PageResult<ProjectPageQueryResultDto>();

            var select = Db.Select<ProjectEntity>()
                            .WhereIf(!query.Name.IsNullOrEmpty(), p => p.Name == query.Name)
                            .WhereIf(!query.Desc.IsNullOrEmpty(), p => p.Desc.Contains(query.Desc));

            var list = await select
                            .OrderBy(!String.IsNullOrEmpty(query.Order) ? query.Order : Consts.DefaultOrder)
                            .Page(query)
                            .ToListAsync<ProjectPageQueryResultDto>();

            result.Data = list;
            result.TotalCount = query.Count;

            return result;
        }

        /// <summary>
        /// 更新项目
        /// </summary>
        /// <param name="update"></param>
        /// <returns></returns>
        public override async Task<BaseResult> UpdateAsync(ProjectUpdateDto update)
        {
            var updateProperties = update.FilterNonDefaultProperties();

            var affRows = await UpdateDtoByIdAsync(update.Id, updateProperties);

            return new BaseResult().Success($"影响行数:{affRows}");
        }
    }
}
